package com.cn.chaomeng.controller;

import com.alibaba.fastjson.JSONObject;
import com.cn.chaomeng.constant.SysParam;
import com.cn.chaomeng.enums.PayStateEnums;
import com.cn.chaomeng.service.ExChangeService;
import com.cn.chaomeng.utils.DateUtil;
import com.cn.chaomeng.utils.HttpUtils;
import com.cn.chaomeng.vo.app.FoodVO;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author 范中燊
 * @version V1.0
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: TODO
 * @date ${date} ${time}
 */
@Controller
@RequestMapping("/wxpay")
public class WxPayController
{

    private final static Logger logger = Logger.getLogger(WxPayController.class);

    @Autowired
    private ExChangeService exChangeService;

    @ResponseBody
    @RequestMapping("/fail")
    public Object payFail(@RequestParam("orderId") String orderId)
    {
        Map<String, Object> resMap = new HashMap<String, Object>();

        Map<String, Object> searchMap = new HashMap<String, Object>();
        searchMap.put("state", SysParam.FAIL_PAY_STATE);
        searchMap.put("orderid", orderId);
        exChangeService.setOrderState(searchMap);

        resMap.put("code", "200");
        return resMap;
    }

    @ResponseBody
    @RequestMapping("/order_state")
    public Object orderState(@RequestParam("orderId") String orderId)
    {

        Map<String, Object> resMap = new HashMap<String, Object>();
        resMap.put("result", false);
        resMap.put("state", SysParam.NO_PAY_STATE);

        String state = exChangeService.getOrderState(orderId);

        if (!SysParam.NO_PAY_STATE.equals(state))
        {
            resMap.put("result", true);
            resMap.put("state", state);
            resMap.put("msg", PayStateEnums.getSjjkCode(state).getReason());
        }
        return resMap;
    }

    @RequestMapping("/success")
    public ModelAndView paySuccess(@RequestParam("openId") String openId, @RequestParam("orderId") String orderId,
        @RequestParam("time") String time)
        throws IOException
    {
        Map<String, Object> resMap = new HashMap<String, Object>();

        Map<String, Object> searchMap = new HashMap<String, Object>();
        searchMap.put("state", SysParam.SUCCESS_PAY_STATE);
        searchMap.put("orderid", orderId);

        // 修改状态
        exChangeService.setOrderState(searchMap);

        List<FoodVO> foodVOList = exChangeService.selectFoodVOs(searchMap);

        StringBuilder name = new StringBuilder();
        double sum = 0;
        for (int i = 0; i < foodVOList.size(); i++)
        {
            sum = foodVOList.get(i).getTotalprices();
            name = name.append(foodVOList.get(i).getFoodName());
            if (i == 2)
            {
                name = name.append("…");
                break;
            }
            if (foodVOList.size() > 1)
            {
                name = name.append(",");
            }
        }

        resMap.put("sum", sum);
        resMap.put("orderId", orderId);
        resMap.put("name", name);
        resMap.put("openId", openId);
        resMap.put("time", DateUtil.timeStamp2Date(time, DateUtil.DATETIME_DEFAULT_FORMAT));
        return new ModelAndView("app/success", resMap);
    }

    /**
     * 微信内H5调起支付
     *
     * @param openId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/jspay")
    public Object jsPay(@RequestParam("openId") String openId, @RequestParam("orderId") String orderId)
    {
        Map result = new HashMap();
        logger.info("****正在支付的openId****" + openId);

        Map<String, Object> searchMap = new HashMap<String, Object>();
        searchMap.put("orderid", orderId);
        List<FoodVO> foodVOList = exChangeService.selectFoodVOs(searchMap);
        StringBuilder name = new StringBuilder();
        for (int i = 0; i < foodVOList.size(); i++)
        {
            name = name.append(foodVOList.get(i).getFoodName());
            if (i == 2)
            {
                name = name.append("…");
                break;
            }
            if (foodVOList.size() > 1)
            {
                name = name.append(",");
            }
        }

        // 统一下单
        Map<String, String> postMap = new HashMap<String, String>();
        postMap.put("price", foodVOList.get(0).getTotalprices() + "");
        postMap.put("openid", openId);
        postMap.put("pay_title", name.toString());
        postMap.put("order_id", orderId);

        String resJsonStr = null;
        try
        {
            resJsonStr = HttpUtils.post("https://b.yifanpay.com/pay/hjpay", postMap);
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
            result.put("resultCode", "FALSE");
            result.put("data", "网络连接错误");
            return result;
        }

        JSONObject jsonRes = JSONObject.parseObject(resJsonStr);

        if (jsonRes.getBoolean("result"))
        {
            JSONObject jsonResData = jsonRes.getJSONObject("data");
            result.put("resultCode", "SUCCESS");
            result.put("data", JSONObject.parseObject(jsonResData.getString("jsapi")));
        }
        else
        {
            result.put("resultCode", "FALSE");
            result.put("data", jsonRes.getString("msg"));
        }

        /**** 返回对象给页面 ****/
        return result;
    }

    /**
     * 获取随机字符串 Nonce Str
     *
     * @return String 随机字符串
     */
    public static String generateNonceStr()
    {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }

}
